package com.openswimsoftware.orm.model.db;

import com.openswimsoftware.orm.ORM;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class ModelDBHelper extends SQLiteOpenHelper {
	
	public ModelDBHelper(Context context)
	{
		super(context, ORM.DATABASE_NAME + ".db", null, ORM.DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) 
	{
		Log.d("orm", "Creating database: " + ORM.DATABASE_NAME);
		this.getDBCreate().onCreate(db);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVer, int newVer) 
	{
		Log.d("orm", "Upgrading database: " + ORM.DATABASE_NAME + " version " + oldVer + "->" + newVer);
		this.getDBCreate().onUpgrade(db, oldVer, newVer);
	}
	
	private DBCreate getDBCreate()
	{
		try 
		{
			return (DBCreate) Class.forName(ORM.DATABASE_CREATE_CLASS).newInstance();
		} 
		catch (InstantiationException e) 
		{
			Log.e("ORM", "Could not instantiate DB create: " + ORM.DATABASE_CREATE_CLASS);
			e.printStackTrace();
		} 
		catch (IllegalAccessException e) 
		{
			Log.e("ORM", "Could not access DB create: " + ORM.DATABASE_CREATE_CLASS);
			e.printStackTrace();
		} 
		catch (ClassNotFoundException e) 
		{
			Log.e("ORM", "Could not finde class DB create: " + ORM.DATABASE_CREATE_CLASS);
			e.printStackTrace();
		}
		
		return null;
	}
}
